// 导航组件加载器 - 简化版本
function loadNavigation() {
    return fetch('components/nav.html')
        .then(response => response.text())
        .then(html => {
            // 将导航HTML插入到页面中
            const navContainer = document.getElementById('nav-container');
            if (navContainer) {
                navContainer.innerHTML = html;
            } else {
                // 如果没有指定容器，插入到body开头
                document.body.insertAdjacentHTML('afterbegin', html);
            }
            
            // 加载导航样式
            loadNavStyles();
            
            // 立即初始化导航功能
            initNavigationFeatures();
        })
        .catch(error => {
            console.error('导航组件加载失败:', error);
            // 如果加载失败，创建一个简单的导航作为备用
            createFallbackNavigation();
        });
}

// 加载导航样式
function loadNavStyles() {
    const existingLink = document.querySelector('link[href="css/nav.css"]');
    if (!existingLink) {
        const link = document.createElement('link');
        link.rel = 'stylesheet';
        link.href = 'css/nav.css';
        document.head.appendChild(link);
    }
}

// 创建备用导航
function createFallbackNavigation() {
    const navContainer = document.getElementById('nav-container');
    if (navContainer) {
        navContainer.innerHTML = `
            <header>
                <nav class="main-nav">
                    <div class="logo">
                        <img src="https://cfcyunchat-1314260234.cos.ap-nanjing.myqcloud.com/pc/%E9%87%91%E9%A1%BE%E4%BA%91logo.jpg" alt="金顾云logo">
                    </div>
                    
                    <button class="mobile-menu-toggle" id="mobileMenuToggle">
                        <span></span>
                        <span></span>
                        <span></span>
                    </button>
                    
                    <div class="nav-menu" id="navMenu">
                        <ul>
                            <li><a href="index.html">首页</a></li>
                            <li><a href="finance-outsourcing-center.html">融资外包</a></li>
                            <li><a href="consultant.html">常顾服务</a></li>
                            <li><a href="club.html">金顾云俱乐部</a></li>
                            <li><a href="about.html">关于金顾云</a></li>
                        </ul>
                        
                        <!-- 移动端按钮 -->
                        <div class="nav-buttons mobile-buttons">
                            <a href="https://client.cfcyun.com/#/login?redirect=%2Fstaging" class="btn btn-login" target="_blank">登录</a>
                            <a href="apply-partner.html" class="btn btn-partner">申请加盟</a>
                            <a href="apply-financing.html" class="btn btn-financing">我要融资</a>
                        </div>
                    </div>
                    
                    <div class="nav-buttons desktop-buttons">
                        <a href="https://client.cfcyun.com/#/login?redirect=%2Fstaging" class="btn btn-login" target="_blank">登录</a>
                        <a href="apply-partner.html" class="btn btn-partner">申请加盟</a>
                        <a href="apply-financing.html" class="btn btn-financing">我要融资</a>
                    </div>
                </nav>
            </header>
        `;
        initNavigationFeatures();
    }
}

// 初始化导航功能
function initNavigationFeatures() {
    console.log('开始初始化导航功能');
    
    // 等待DOM渲染完成
    setTimeout(() => {
        initMobileNavigation();
        initDropdownMenus();
        setActiveNavigation();
        console.log('导航功能初始化完成');
    }, 100);
}

// 移动端导航菜单初始化
function initMobileNavigation() {
    const mobileMenuToggle = document.getElementById('mobileMenuToggle');
    const navMenu = document.getElementById('navMenu');
    
    console.log('查找移动端菜单元素:', {
        toggle: !!mobileMenuToggle,
        menu: !!navMenu,
        windowWidth: window.innerWidth
    });
    
    if (mobileMenuToggle && navMenu) {
        console.log('移动端菜单元素找到，绑定点击事件');
        
        // 移除之前的事件监听器（如果有的话）
        const newToggle = mobileMenuToggle.cloneNode(true);
        mobileMenuToggle.parentNode.replaceChild(newToggle, mobileMenuToggle);
        
        // 重新获取元素
        const freshToggle = document.getElementById('mobileMenuToggle');
        const freshMenu = document.getElementById('navMenu');
        
        // 绑定点击事件
        freshToggle.addEventListener('click', function(e) {
            e.preventDefault();
            e.stopPropagation();
            
            console.log('汉堡菜单被点击！');
            
            const isActive = freshMenu.classList.contains('active');
            console.log('当前菜单状态:', isActive ? '打开' : '关闭');
            
            if (isActive) {
                // 关闭菜单
                freshMenu.classList.remove('active');
                freshToggle.classList.remove('active');
                document.body.style.overflow = '';
                console.log('菜单已关闭');
            } else {
                // 打开菜单
                freshMenu.classList.add('active');
                freshToggle.classList.add('active');
                document.body.style.overflow = 'hidden';
                console.log('菜单已打开');
            }
        });
        
        // 点击菜单外部关闭
        document.addEventListener('click', function(e) {
            if (!freshMenu.contains(e.target) && !freshToggle.contains(e.target)) {
                freshMenu.classList.remove('active');
                freshToggle.classList.remove('active');
                document.body.style.overflow = '';
            }
        });
        
        // 窗口大小改变时关闭移动端菜单
        window.addEventListener('resize', function() {
            if (window.innerWidth > 768) {
                freshMenu.classList.remove('active');
                freshToggle.classList.remove('active');
                document.body.style.overflow = '';
            }
        });
        
        console.log('移动端导航事件绑定完成');
    } else {
        console.error('移动端菜单元素未找到！');
        // 输出更多调试信息
        console.log('所有ID元素:', Array.from(document.querySelectorAll('[id]')).map(el => el.id));
    }
}

// 下拉菜单交互
function initDropdownMenus() {
    const dropdownTriggers = document.querySelectorAll('.has-dropdown');
    
    dropdownTriggers.forEach(trigger => {
        const dropdownToggle = trigger.querySelector('.dropdown-toggle');
        
        if (dropdownToggle) {
            // 移动端：点击切换
            dropdownToggle.addEventListener('click', function(e) {
                e.preventDefault();
                e.stopPropagation();
                
                // 如果是移动端模式
                if (window.innerWidth <= 768) {
                    trigger.classList.toggle('active');
                }
            });
        }
    });
}

// 设置当前页面的导航高亮
function setActiveNavigation() {
    const currentPage = window.location.pathname.split('/').pop() || 'index.html';
    const navLinks = document.querySelectorAll('.nav-menu a');
    
    navLinks.forEach(link => {
        link.classList.remove('active');
        const href = link.getAttribute('href');
        if (href === currentPage || (currentPage === '' && href === 'index.html')) {
            link.classList.add('active');
        }
    });
}

// 页面加载完成后自动加载导航
document.addEventListener('DOMContentLoaded', function() {
    console.log('DOM加载完成，开始加载导航组件');
    loadNavigation();
});

// 确保在页面完全加载后再次检查导航
window.addEventListener('load', function() {
    // 如果导航还没有初始化，再次尝试
    if (!document.getElementById('mobileMenuToggle')) {
        console.log('页面完全加载后重新检查导航');
        setTimeout(() => {
            if (!document.getElementById('mobileMenuToggle')) {
                createFallbackNavigation();
            }
        }, 500);
    }
});